package org.answer.controller;

import org.answer.constant.MessageConstant;
import org.answer.entity.Result;
import org.answer.pojo.OrderSetting;
import org.answer.service.BehaviorLogService;
import org.answer.service.OrderSettingService;
import org.answer.utils.BehaviorLogUtils;
import org.answer.utils.GetUserNameUtils;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.answer.utils.POIUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();

    @Reference
    private OrderSettingService orderSettingService;

    @Reference
    private BehaviorLogService behaviorLogService;

    //文件上传，实现预约设置数据批量导入
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request){

        try {
            List<String[]> list = POIUtils.readExcel(excelFile);//使用POI解析表格数

            List<OrderSetting> data = new ArrayList<>();
            for (String[] strings : list) {
                String orderDate = strings[0];
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(new Date(orderDate),Integer.parseInt(number));
                data.add(orderSetting);
            }
            //通过dubbo远程调用服务实现数据批量导入到数据库
            orderSettingService.add(data);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.IMPORT_ORDERSETTING_SUCCESS
                    )
            );
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.IMPORT_ORDERSETTING_FAIL
                    )
            );
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            //  文件解析失败
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }


    /**
     * 根据日期查询预约设置数据，（获取指定日期所在月份的预约设置）
     * @return
     */
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){
        try {
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    /**
     * 根据指定日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @RequestMapping("/editNumberByDate")
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting, HttpServletRequest request){

        try{
            orderSettingService.editNumberByDate(orderSetting);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ORDERSETTING_SUCCESS
                    )
            );
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ORDERSETTING_FAIL
                    )
            );
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
